﻿using Azylee.Core.IOUtils.DirUtils;
using Azylee.Core.IOUtils.TxtUtils;
using Emgu.CV.Dai;
using JMBox.Task;
using JMBox.Util;
using JMBox.Utils;
using JMBox.Utils.Log;
using JMLibrary.Codes;
using JMLibrary.Hooks;
using JustMetClient.Forms.View;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using TestKeyboard.PressKey;
using static JMBox.Config.R;

namespace JMBox
{
    public partial class MainForm : Form
    {
        public static DateTime LastClearFloorDateTime = DateTime.Now;
        //创建任务对象
        private ShutNetTask shutNetTask;
        private ConnectNetTask connectNetTask;
        private ClearTask clearTask;
        private AutoLockTask autoLockTask;
        //用户鼠标键盘信息获取（鼠标键盘钩子）
        private static UserActivityHook _userActivityHook;
        //当前窗体状态
        private FormWindowState _fwsPrevious;
        //功能说明
        private List<string> functionDesc = new List<string>();
        public static String keyDriverType = "DD";
        public IPressKey mPressKey;

        #region 窗体行为

        public MainForm()
        {
            InitializeComponent();
            InitDir();
            //初始化任务对象
            shutNetTask = new ShutNetTask();
            connectNetTask = new ConnectNetTask();
            clearTask = new ClearTask();
            autoLockTask = new AutoLockTask();
            //绑定鼠标键盘钩子
            _userActivityHook = new UserActivityHook(Config.R.Contact.Module);
            _userActivityHook.OnMouseActivity += new MouseEventHandler(Hook_MouseOnClick);
            _userActivityHook.KeyDown += new KeyEventHandler(Hook_KeyDown);
            _userActivityHook.Start();
            //悬浮窗初始化
            _fwsPrevious = this.WindowState;
            Contact.TopUI = new TopForm(this);
            LoadFileList();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            clearTask.Start();
            openCheckThread();
        }

        /// <summary>
        /// 退出APP
        /// </summary>
        public void ExitApp()
        {
            _userActivityHook.Stop();
            InnerExitApp();
        }

        public void InnerExitApp()
        {
            //关闭正在执行的任务
            clearTask.End();
            GlobalStatus.OpenAutoMolong = false;
            GlobalStatus.AppIsRuning = false;
            GlobalStatus.OpenCheckThread = false;
            GlobalStatus.RefreshIsOpen = false;
            Application.Exit();
            Application.Exit();
            Application.Exit();
            Environment.Exit(0);
        }
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _userActivityHook.Stop();
        }

        #endregion

        #region Hook代码

        private DateTime lastClickTime = DateTime.MinValue;

        /// <summary>
        /// 鼠标点击位置记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hook_MouseOnClick(object sender, MouseEventArgs e)
        {
            if (e.Clicks > 0)
            {

            }
        }

        private void Hook_KeyDown(object sender, KeyEventArgs e)
        {
            if (!GlobalConfig.IsAlive())
            {
                MessageBox.Show("已过期");
                return;
            }
            //全局开关
            if (e.KeyCode == WinKeyTool.GetWinKeyByStr(GlobalConfig.AllFunTriggerKey))
            {
                if (GlobalStatus.AllFunOpenFlag)
                {
                    GlobalStatus.AllFunOpenFlag = false;
                }
                else
                {
                    GlobalStatus.AllFunOpenFlag = true;
                }

                Tb_All_Fun_Status.Text = GlobalStatus.AllFunOpenFlag ? "开启" : "关闭";

            }

            if (GlobalStatus.AllFunOpenFlag)
            {
                //断网+联网
                if (e.KeyCode == Keys.F4)
                {
                    shutNetTask.Start();
                    //休眠3秒
                    Thread.Sleep(3 * 1000);
                    connectNetTask.Start();

                }
                //自动Lock
                else if (e.KeyCode == Keys.F5)
                {
                    if (GlobalStatus.OpenAutoLock)
                    {
                        GlobalStatus.OpenAutoLock = false;
                        AutoLockTask.RunTask = false;
                        Tb_Auto_Lock_Key.Text = "关闭";
                    }
                    else
                    {
                        GlobalStatus.OpenAutoLock = true;
                        AutoLockTask.RunTask = true;
                        autoLockTask.Start();
                        Tb_Auto_Lock_Key.Text = "开启";
                    }

                }
                //开启自动魔龙
                else if (e.KeyCode == Keys.F6)
                {
                    Logger.Default.Info("KEY F6");
                    OneAutoStep();
                }
                //关闭自动魔龙
                else if (e.KeyCode == Keys.F9)
                {
                    Logger.Default.Info("KEY F9");
                    GlobalStatus.OpenAutoMolong = false;
                    isAutoMolongRunning = false;
                }
                //开启自动Space
                else if (e.KeyCode == WinKeyTool.GetWinKeyByStr(GlobalConfig.ClearTriggerKey))
                {
                    if (!GlobalStatus.OpenClear)
                    {
                        GlobalStatus.OpenClear = true;
                        ClearTask.RunTask = true;
                        clearTask.Start();
                        Contact.TopUI.RefleshTipColor();
                    }
                }
                //关闭自动Space
                else if (e.KeyCode == WinKeyTool.GetWinKeyByStr(GlobalConfig.ClearStopKey))
                {
                    GlobalStatus.OpenClear = false;
                    ClearTask.RunTask = false;
                    Contact.TopUI.RefleshTipColor();
                }
            }
        }
        #endregion

        #region 窗口的关闭和隐藏
        /// <summary>
        /// 隐藏主界面窗口
        /// </summary>
        private void HideForm()
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            //展示悬浮窗
            if (Contact.TopUI == null)
            {
                Contact.TopUI = new TopForm(this);
            }
            else
            {
                //如果悬浮窗是最小化，则展示悬浮窗
                if (Contact.TopUI.WindowState == FormWindowState.Minimized)
                {
                    Contact.TopUI.WindowState = FormWindowState.Normal;
                    Contact.TopUI.Activate();
                }
                Contact.TopUI.Show();
                Contact.TopUI.ShowInTaskbar = false;
            }
            //记录当前窗体状态
            _fwsPrevious = WindowState;

        }
        /// <summary>
        /// 显示窗口
        /// </summary>
        private void ShowForm()
        {
            if (Contact.TopUI != null)
            {
                Contact.TopUI.Hide();
            }
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.Activate();
            _fwsPrevious = this.WindowState;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            HideForm();
            switch (e.CloseReason)
            {
                case CloseReason.None:
                    e.Cancel = true;
                    break;
                case CloseReason.WindowsShutDown:
                    break;
                case CloseReason.MdiFormClosing:
                    e.Cancel = true;
                    break;
                case CloseReason.UserClosing:
                    e.Cancel = true;
                    break;
                case CloseReason.TaskManagerClosing:
                    e.Cancel = true;
                    break;
                case CloseReason.FormOwnerClosing:
                    e.Cancel = true;
                    break;
                case CloseReason.ApplicationExitCall:
                    break;
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //最小化时所需的操作
                //this.Hide();
                this.ShowInTaskbar = false;
                Contact.TopUI.Show();
            }
        }

        //保存窗体状态
        public void RestoreWindow()
        {
            ShowForm();
        }

        #endregion

        #region 基础功能说明

        public void UpdateFunctionDesc()
        {
            functionDesc.Add("▶ " + "按”" + GlobalConfig.ClearTriggerKey + "”键" + "自动断网+联网");
            functionDesc.Add("▶ " + "按”" + GlobalConfig.ClearTriggerKey + "”键" + "自动拾取");
            functionDesc.Add("▶ " + "按”" + GlobalConfig.ClearStopKey + "”键" + "关闭拾取");
            //更新偏移量数据
            Tb_MIME_Obj_X.Text = GlobalConfig.MIME_OBJ_OFFSET_X.ToString();
            Tb_MIME_Obj_Y.Text = GlobalConfig.MIME_OBJ_OFFSET_Y.ToString();
            Tb_Target_Obj_X.Text = GlobalConfig.TARGET_OBJ_OFFSET_X.ToString();
            Tb_Target_Obj_Y.Text = GlobalConfig.TARGET_OBJ_OFFSET_Y.ToString();
            Tb_Target_Match.Text = GlobalConfig.MatchThreshold.ToString();
            //更新基础状态
            Tb_All_Fun_Status.Text = "开启";
            Tb_Auto_Lock_Key.Text = "关闭";
            Tb_Right_Lock_Key.Text = "关闭";
            Tb_Center_X.Text = GlobalConfig.CENTER_POI_X.ToString();
            Tb_Center_Y.Text = GlobalConfig.CENTER_POI_Y.ToString();
            //设置SC默认选中
            CheckBox_Auto_SC.Checked = true;


        }

        #endregion

        #region 按钮区


        private void Btn_Base_Funs_Desc_Click(object sender, EventArgs e)
        {
            string message = string.Join("\n", functionDesc);
            MessageBox.Show("功能\n" + message);
        }

        private void Btn_Img_Select_Click(object sender, EventArgs e)
        {


        }

        private void Btn_Img_Poi_Click(object sender, EventArgs e)
        {
            String imgPath = Tb_Img_Poi_Path.Text.ToString();
            if (String.IsNullOrEmpty(imgPath))
            {
                MessageBox.Show("请选择一张图片");
                return;
            }

            double screenProportion = ImgPoiTool.CaptureScreen(Contact.ScreenImgPath);
            Logger.Default.Info("screenProportion:" + screenProportion);
            Location loc = ImgPoiTool.LocateOnTargetImgSimple(Contact.ScreenImgPath, imgPath, screenProportion, true);
            Logger.Default.Info("坐标:" + loc.X + "|" + loc.Y + "|" + loc.Macth);
            Tb_Img_Poi_X.Text = loc.X.ToString();
            Tb_Img_Poi_Y.Text = loc.Y.ToString();
        }

        private void Btn_Open_Poi_Dir_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("explorer.exe", Contact.ScreenImgDirPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件夹打开失败");
            }
        }

        private void Btn_Mime_Obj_Save_Click(object sender, EventArgs e)
        {
            String x_offset = Tb_MIME_Obj_X.Text.ToString();
            if (String.IsNullOrEmpty(x_offset))
            {
                MessageBox.Show("请输入X偏移");
                return;
            }
            String y_offset = Tb_MIME_Obj_Y.Text.ToString();
            if (String.IsNullOrEmpty(y_offset))
            {
                MessageBox.Show("请输入Y偏移");
                return;
            }
            //保存到配置文件
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.MIME_OBJ_OFFSET_X_Str, x_offset);
            GlobalConfig.MIME_OBJ_OFFSET_X = int.Parse(x_offset);
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.MIME_OBJ_OFFSET_Y_Str, y_offset);
            GlobalConfig.MIME_OBJ_OFFSET_Y = int.Parse(y_offset);

        }

        private void Btn_Target_Obj_Save_Click(object sender, EventArgs e)
        {
            String x_offset = Tb_Target_Obj_X.Text.ToString();
            if (String.IsNullOrEmpty(x_offset))
            {
                MessageBox.Show("请输入X偏移");
                return;
            }
            String y_offset = Tb_Target_Obj_Y.Text.ToString();
            if (String.IsNullOrEmpty(y_offset))
            {
                MessageBox.Show("请输入Y偏移");
                return;
            }
            //保存到配置文件
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.TARGET_OBJ_OFFSET_X_Str, x_offset);
            GlobalConfig.TARGET_OBJ_OFFSET_X = int.Parse(x_offset);
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.TARGET_OBJ_OFFSET_Y_Str, y_offset);
            GlobalConfig.TARGET_OBJ_OFFSET_Y = int.Parse(y_offset);
        }

        #endregion

        #region 功能区2


        private void Btn_Target_Match_Click(object sender, EventArgs e)
        {
            String match = Tb_Target_Match.Text.ToString();
            if (String.IsNullOrEmpty(match))
            {
                MessageBox.Show("请输入匹配度");
                return;
            }
            //保存到配置文件
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.MatchThresholdStr, match);
            GlobalConfig.MatchThreshold = double.Parse(match);
        }

        public IPressKey GetPressKey()
        {
            bool bInitResult = false;
            switch (keyDriverType)
            {
                case "DD":
                    if (mPressKey == null)
                    {
                        mPressKey = new PressKeyByDD();
                        bInitResult = mPressKey.Initialize(EnumWindowsType.Win64);
                        if (bInitResult == false)
                        {
                            MessageBox.Show("组件初始化失败");
                        }
                    }
                    break;
                case "WINIO":
                    if (mPressKey == null)
                    {
                        mPressKey = new PressKeyByWinIO();
                        bInitResult = mPressKey.Initialize(EnumWindowsType.Win64);
                        if (bInitResult == false)
                        {
                            MessageBox.Show("组件初始化失败");
                        }
                    }
                    break;
                case "WINAPI":
                    if (mPressKey == null)
                    {
                        mPressKey = new PressKeyByKeyboard();
                        bInitResult = mPressKey.Initialize(EnumWindowsType.Win64);
                        if (bInitResult == false)
                        {
                            MessageBox.Show("组件初始化失败");
                        }
                    }
                    break;
                case "WINRING0":
                default:
                    if (mPressKey == null)
                    {
                        mPressKey = new PressKeyByWinRing0();
                        //只有64位实现，EnumWindowsType不生效
                        bInitResult = mPressKey.Initialize(EnumWindowsType.Win64);
                        if (bInitResult == false)
                        {
                            MessageBox.Show("组件初始化失败");
                        }
                    }
                    break;

            }
            return mPressKey;

        }

        private void Cb_Key_Driver_Now_Select_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = Cb_Key_Driver_Now_Select.Text.ToString();
            if (!string.IsNullOrEmpty(type))
            {
                keyDriverType = type;
                mPressKey = null;
            }
        }

        private void CheckBox_Auto_Left_CheckedChanged(object sender, EventArgs e)
        {
            AutoLockTask.AUTO_LEFT = CheckBox_Auto_Left.Checked;
        }

        private void CheckBox_Auto_Right_CheckedChanged(object sender, EventArgs e)
        {
            AutoLockTask.AUTO_RIGHT = CheckBox_Auto_Right.Checked;
        }

        private void Btn_Auto_Lock_Speed_Click(object sender, EventArgs e)
        {
            string speed = Tb_Auto_Lock_Speed.Text;
            if (string.IsNullOrEmpty(speed))
            {
                MessageBox.Show("请设置一个准确的频率");
            }
            try
            {
                int iSpeed = int.Parse(speed);
                AutoLockTask.AUTO_LOCK_SPEED = iSpeed;
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置频率错误:" + ex.Message);
            }
        }

        private void Btn_Load_Img_List_Click(object sender, EventArgs e)
        {
            LoadFileList();
        }

        public void LoadFileList()
        {
            // 清除ListView中现有的项
            ListView_ImgList.Items.Clear();
            AutoLockTask.TargetImgPaths.Clear();

            // 定义支持的图片格式
            string[] extensions = new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };

            // 获取指定路径下的所有文件
            string[] files = Directory.GetFiles(Contact.MatchImgDirPath);

            foreach (string file in files)
            {
                // 获取文件的扩展名
                string extension = Path.GetExtension(file).ToLower();

                // 检查文件是否是支持的图片格式
                if (Array.IndexOf(extensions, extension) >= 0)
                {
                    // 将文件名添加到ListView中
                    ListView_ImgList.Items.Add(Path.GetFileName(file));
                    AutoLockTask.TargetImgPaths.Add(DirTool.Combine(Contact.MatchImgDirPath, Path.GetFileName(file)));
                }
            }
        }

        /// <summary>
        /// 初始化文件夹
        /// </summary>
        public void InitDir()
        {
            if (!Directory.Exists(Contact.ScreenImgDirPath))
            {
                Directory.CreateDirectory(Contact.ScreenImgDirPath);
            }

            if (!Directory.Exists(Contact.MatchImgDirPath))
            {
                Directory.CreateDirectory(Contact.MatchImgDirPath);
            }
        }

        private void ListView_ImgList_MouseClick(object sender, MouseEventArgs e)
        {
            if (ListView_ImgList.SelectedItems.Count > 0)
            {
                ListViewItem item = ListView_ImgList.SelectedItems[0];
                string imgPath = item.Text;
                if (string.IsNullOrEmpty(imgPath))
                {
                    MessageBox.Show("未选择文件！");
                    return;
                }
                string realImgPath = DirTool.Combine(Contact.MatchImgDirPath, imgPath);

                Logger.Default.Info("filePath:" + realImgPath);

                //输入文件
                Tb_Img_Poi_Path.Text = realImgPath;
                // 创建一个Image对象
                Image image = Image.FromFile(realImgPath);

                // 将图片赋值给PictureBox
                Pb_Img_Poi_Target.Image = image;

                // 设置SizeMode为Zoom以使图片自适应PictureBox，同时保持纵横比
                Pb_Img_Poi_Target.SizeMode = PictureBoxSizeMode.Zoom;

                AutoLockTask.NowImgPath = realImgPath;
            }
        }

        #endregion

        private volatile bool isAutoMolongRunning = false;
        public void OneAutoStep()
        {
            if (!isAutoMolongRunning && !GlobalStatus.OpenAutoMolong)
            {
                GlobalStatus.OpenAutoMolong = true;
                isAutoMolongRunning = true;
                Thread t = new Thread(auto_molong_task);
                t.Start();
            }
        }

        #region First-ML


        //SUCCESS COUNT
        public int FINISH_COUNT = 0;
        //WAIT TIME
        public int WAIT_TIME = 0;

        public void auto_molong_task()
        {
            Logger.Default.Info("【START MOLONG TASK】");
            int count = 0;
            while (GlobalStatus.AppIsRuning && GlobalStatus.OpenAutoMolong)
            {

                count++;
                Logger.Default.Info("【NOW IS " + count + "】");
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                killBoss();
                stopwatch.Stop();
                FINISH_COUNT = count;
                Logger.Default.Info("【NOW EXECUTE USE " + stopwatch.Elapsed.TotalSeconds + " S】");
                //wait map 5 min
                int interval = 0;
                while (interval < 310 && GlobalStatus.OpenAutoMolong)
                {
                    interval++;
                    WAIT_TIME = interval;
                    Thread.Sleep(1000);
                }
                Logger.Default.Info("【FINISH WAIT MAP】");
            }
        }

        public void killBoss()
        {
            if (goMLMap())
            {
                if (GlobalStatus.OpenAutoShaChong)
                {
                    goSCMap();
                }
                exitMolong(true);
            }
        }

        public bool goMLMap()
        {
            LocAndClick("20_i_know.jpg");
            sleepTagrget(1000, 2000);
            //get focus
            clickCenterMouseLeft();
            //auto space
            for (int i = 0; i < 6; i++)
            {
                Contact.MainUI.GetPressKey().KeyPress(Keys.Space);
                sleepTagrget(GlobalConfig.ClearRandomMin, GlobalConfig.ClearRandomMax);
            }
            Thread.Sleep(1000);
            Location loc_shahe_selected = getTargetImgLocation("1_shahe_selected.jpg");
            if (loc_shahe_selected.X != -1)
            {
                LocAndClick("3_fuben_tag.jpg");
            }
            LocAndClick("2_molong_map.jpg");
            if (!LocAndClick("4_create_room.jpg"))
            {
                return false;
            }
            if (!LocAndClick("5_like_jinru.jpg"))
            {
                return false;
            }
            //map switch，loading...
            sleepTagrget(5000, 7000);
            LocAndClick("20_i_know.jpg");
            sleepTagrget(1000, 2000);
            if (!checkIsMLMap())
            {
                return false;
            }
            bool status = modifyUserMoLongPoi();
            //can't modify
            if (!status)
            {
                exitMolong(true);
                return false;
            }
            if (!yzszGotoMolong())
            {
                return false;
            }
            autoAttackMolong();
            if (!checkIsMLMap())
            {
                return false;

            }
            clearFloorMolong();
            sleepTagrget(2000, 3000);
            return true;
        }

        public Location getTargetImgLocation(string imgName)
        {
            string imgPath = DirTool.Combine(Contact.MolongImgDirPath, imgName);
            Location loc = ImgPoiTool.LocateSimple(imgPath);
            if (loc.X == -1)
            {
                loc = ImgPoiTool.LocateSimple(imgPath);
            }
            Logger.Default.Info(imgName + "poi result:" + loc.X + "|" + loc.Y);

            return loc;
        }

        public void autoAttackMolong()
        {
            autoAttackGhost("9_molong_alive.jpg", "MOLONG");
        }

        public bool yzszGotoMolong()
        {
            //get focus
            clickCenterMouseLeft();
            //X
            keyPressWithTime(Keys.X, 200);
            sleepTagrget(1800, 2200);
            //check is ml
            if (checkIsMLMap())
            {
                //up 10s
                keyPressWithTime(Keys.W, 10000);
                Thread.Sleep(200);
                keyPressWithTime(Keys.W, 500);
                Logger.Default.Info("ARRIVED MOLONG.");
                return true;
            }
            return false;
        }

        public Location getMlMapFlag()
        {
            string molong_flag = DirTool.Combine(Contact.MolongImgDirPath, "12_molong_map_flag.jpg");
            Location loc_molong_flag = ImgPoiTool.LocateSimple(molong_flag);
            Logger.Default.Info("in molong map result 1:" + loc_molong_flag.X + "|" + loc_molong_flag.Y);
            if (loc_molong_flag.X == -1)
            {
                loc_molong_flag = ImgPoiTool.LocateSimple(molong_flag);
                Logger.Default.Info("in molong map result 2:" + loc_molong_flag.X + "|" + loc_molong_flag.Y);
            }
            return loc_molong_flag;
        }

        public bool exitMolong(bool again)
        {
            //not molong, don't exit
            if (checkIsMLMap())
            {
                Logger.Default.Info("NOW IS IN ML MAP, START JIESUAN");
                //ESC
                Contact.MainUI.GetPressKey().KeyPress(Keys.Escape);
                Thread.Sleep(2000);
                //jie_suan
                LocAndClick("10_jiesuan.jpg");
                Thread.Sleep(1000);
                //confirm
                LocAndClick("11_queren.jpg");
                //check is in molong?
                sleepTagrget(6000, 7000);
                if (!checkIsMLMap())
                {
                    // not in ml map
                    return true;
                }
                else
                {
                    if (again)
                    {
                        prevent_direct();
                        keyPressWithTime(Keys.D, 2000);
                        keyPressWithTime(Keys.S, 500);
                        keyPressWithTime(Keys.D, 500);
                        exitMolong(false);
                    }
                    else
                    {
                        Logger.Default.Info("EXIT ML FAILD, WAIT SYS EXIT");
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// true = in map
        /// </summary>
        /// <returns></returns>
        public bool checkIsMLMap()
        {
            Location loc_molong_flag = getMlMapFlag();
            return loc_molong_flag.X != -1;
        }

        public bool modifyUserMoLongPoi()
        {
            return modifyUserToTargetPoiX("6_molong_yzsz.jpg", Keys.W, 6);
        }

        public void clearFloorMolong()
        {
            Logger.Default.Info("start clear floor molong");
            LastClearFloorDateTime = DateTime.Now;
            Location loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                //开启R
                Contact.MainUI.GetPressKey().KeyPress(Keys.R);
                Contact.MainUI.GetPressKey().KeyPress(Keys.R);
                //ONE
                keyPressWithTime(Keys.A, 1000);
                keyPressWithTime(Keys.W, 500);
                keyPressWithTime(Keys.D, 1500);
                keyPressWithTime(Keys.S, 1000);
                keyPressWithTime(Keys.A, 500);
            }
            loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                //TWO
                keyPressWithTime(Keys.A, 1000);
                keyPressWithTime(Keys.W, 1500);
                keyPressWithTime(Keys.D, 1500);
                keyPressWithTime(Keys.S, 300);
                keyPressWithTime(Keys.A, 1500);
                keyPressWithTime(Keys.S, 300);
                keyPressWithTime(Keys.D, 2000);
                keyPressWithTime(Keys.S, 300);
                keyPressWithTime(Keys.A, 1000);
            }

            //关闭T
            Contact.MainUI.GetPressKey().KeyPress(Keys.T);
            Contact.MainUI.GetPressKey().KeyPress(Keys.T);
        }

        public void clearFloorShaChong()
        {
            Logger.Default.Info("start clear floor shachong");
            LastClearFloorDateTime = DateTime.Now;
            Location loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                //开启R
                Contact.MainUI.GetPressKey().KeyPress(Keys.R);
                Contact.MainUI.GetPressKey().KeyPress(Keys.R);
                //ONE
                keyPressWithTime(Keys.A, 1000);
                keyPressWithTime(Keys.W, 500);
                keyPressWithTime(Keys.D, 1500);
                keyPressWithTime(Keys.S, 500);
                keyPressWithTime(Keys.A, 1500);
            }

            loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                //TWO
                keyPressWithTime(Keys.S, 500);
                keyPressWithTime(Keys.D, 1500);
                keyPressWithTime(Keys.W, 1500);
                keyPressWithTime(Keys.A, 1500);
                keyPressWithTime(Keys.S, 1500);
                keyPressWithTime(Keys.D, 1000);
                keyPressWithTime(Keys.W, 1500);
                keyPressWithTime(Keys.D, 500);
                keyPressWithTime(Keys.S, 1500);
            }


            //关闭T
            Contact.MainUI.GetPressKey().KeyPress(Keys.T);
            Contact.MainUI.GetPressKey().KeyPress(Keys.T);
        }

        public bool LocAndClick(string imgName)
        {
            //NOT SUCCESS，AGAIN
            if (!LocAndClickInner(imgName))
            {
                if (!LocAndClickInner(imgName))
                {
                    return LocAndClickInner(imgName);
                }
            }
            return true;
        }

        public bool LocAndClickInner(string imgName)
        {
            string imgpath = DirTool.Combine(Contact.MolongImgDirPath, imgName);
            Location loc = ImgPoiTool.LocateSimple(imgpath);
            if (loc.X != -1)
            {
                ImgPoiTool.ClickTargetPoi(loc);
                //点击后等待0.7-1.1秒
                sleepTagrget(700, 1100);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 鼠标左键中心位置
        /// </summary>
        public void clickCenterMouseLeft()
        {
            MouseEvent mouseEventD = new MouseEvent(MouseEventType.MouseLeftDown, GlobalConfig.CENTER_POI_X, GlobalConfig.CENTER_POI_Y, 0);
            ImgPoiTool.mouseHook.MouseWork(mouseEventD);
            Thread.Sleep(100);
            MouseEvent mouseEventU = new MouseEvent(MouseEventType.MouseLeftUp, GlobalConfig.CENTER_POI_X, GlobalConfig.CENTER_POI_Y, 0);
            ImgPoiTool.mouseHook.MouseWork(mouseEventU);
        }

        /// <summary>
        /// 鼠标右键中心位置
        /// </summary>
        public void clickCenterMouseRight()
        {
            MouseEvent mouseEventD = new MouseEvent(MouseEventType.MouseRightDown, GlobalConfig.CENTER_POI_X, GlobalConfig.CENTER_POI_Y, 0);
            ImgPoiTool.mouseHook.MouseWork(mouseEventD);
            Thread.Sleep(100);
            MouseEvent mouseEventU = new MouseEvent(MouseEventType.MouseRightUp, GlobalConfig.CENTER_POI_X, GlobalConfig.CENTER_POI_Y, 0);
            ImgPoiTool.mouseHook.MouseWork(mouseEventU);

        }

        public void sleepTagrget(int start, int end)
        {
            int[] duration = RandomNumTool.GenerateRandomNumbers(start, end, 1);
            Thread.Sleep(duration[0]);
        }

        private void Btn_Auto_MoLong_Click(object sender, EventArgs e)
        {

        }

        private void Btn_Save_Center_Poi_Click(object sender, EventArgs e)
        {
            String x_center = Tb_Center_X.Text.ToString();
            if (String.IsNullOrEmpty(x_center))
            {
                MessageBox.Show("请输入X");
                return;
            }
            String y_center = Tb_Center_Y.Text.ToString();
            if (String.IsNullOrEmpty(y_center))
            {
                MessageBox.Show("请输入Y");
                return;
            }
            //保存到配置文件
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.CENTER_POI_X_Str, x_center);
            GlobalConfig.CENTER_POI_X = int.Parse(x_center);
            IniTool.Set(Config.R.Contact.Settings, GlobalConfig.SHConfigHeader, GlobalConfig.CENTER_POI_Y_Str, y_center);
            GlobalConfig.CENTER_POI_Y = int.Parse(y_center);

        }

        #endregion

        #region Second-SC

        public void goSCMap()
        {
            if (!checkIsMLMap())
            {
                return;
            }
            //modify poi, only x
            bool status_ml_to_yzsz_flag = modifyUserToTargetPoiX("15_molong_return_flag.jpg", Keys.S, 6);
            if (!status_ml_to_yzsz_flag)
            {
                return;
            }

            //go to yzsz
            molongGotoYzsz();
            yzszGotoShaChong();
            Thread.Sleep(300);
            autoAttackShaChong();
            clearFloorShaChong();
            Location loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                keyPressWithTime(Keys.D, 7000);
                sleepTagrget(1000, 2000);
            }
        }

        public void molongGotoYzsz()
        {
            //X START
            keyPressWithTime(Keys.X, 200);
            Thread.Sleep(2200);
            //check is ml
            Location loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                //DOWN 8s
                keyPressWithTime(Keys.S, 8000);
                keyPressWithTime(Keys.S, 500);
            }
            //Keep taking small steps
            for (int i = 0; i < 10; i++)
            {
                if (GlobalStatus.OpenAutoMolong)
                {
                    Contact.MainUI.GetPressKey().KeyDown(Keys.S);
                    Thread.Sleep(300);
                    Contact.MainUI.GetPressKey().KeyUp(Keys.S);
                    Thread.Sleep(300);
                    //每走完一次，检测一下是不是看到yzsz
                    string yzsz_flag = DirTool.Combine(Contact.MolongImgDirPath, "6_molong_yzsz.jpg");
                    Location loc_yzsz_flag = ImgPoiTool.LocateSimple(yzsz_flag);
                    Logger.Default.Info("yzsz定位结果:" + loc_yzsz_flag.X + "|" + loc_yzsz_flag.Y);
                    //看到yzsz，break
                    if (loc_yzsz_flag.X != -1)
                    {
                        break;
                    }
                }
            }
        }

        public void autoAttackShaChong()
        {
            autoAttackGhost("17_shachong_alive.jpg", "SHACHONG");
        }

        public void yzszGotoShaChong()
        {
            sleepTagrget(200, 400);
            //check is ml
            Location loc_molong_flag = getMlMapFlag();
            if (loc_molong_flag.X != -1)
            {
                keyPressWithTime(Keys.D, 7400);
                keyPressWithTime(Keys.S, 1000);
                keyPressWithTime(Keys.D, 2000);
                keyPressWithTime(Keys.W, 1300);
                keyPressWithTime(Keys.D, 4000);
            }
            for (int i = 0; i < 1; i++)
            {
                if (GlobalStatus.OpenAutoMolong)
                {
                    keyPressWithTime(Keys.A, 800);
                }
            }

            Logger.Default.Info("ARRIVED SHACHONG.");
        }

        #endregion

        #region Common-Fun

        public void autoAttackGhost(string ghost_alive_img_name, string ghost)
        {
            string ghost_alive_img_path = DirTool.Combine(Contact.MolongImgDirPath, ghost_alive_img_name);
            //往左偏移40
            MouseEvent mouseEventM = new MouseEvent(MouseEventType.MouseMove, GlobalConfig.CENTER_POI_X - 40, GlobalConfig.CENTER_POI_Y, 100);
            ImgPoiTool.mouseHook.MouseWork(mouseEventM);
            Thread.Sleep(500);
            clickCenterMouseLeft();
            //switch wuqi
            keyPressWithTime(Keys.D1, 200);
            keyPressWithTime(Keys.D1, 200);
            bool ghostIsAlive = true;
            int ghost_check_dead_count = 0;
            int moveFlagCount = 0;
            while (ghostIsAlive && GlobalStatus.OpenAutoMolong)
            {
                moveFlagCount++;
                Location loc_ghost_alive = ImgPoiTool.LocateSimple(ghost_alive_img_path);
                Logger.Default.Info(ghost + "ALIVE FLAG POI RESULT:" + loc_ghost_alive.X + "|" + loc_ghost_alive.Y);
                if (loc_ghost_alive.X == -1)
                {
                    ghost_check_dead_count++;
                    if (ghost_check_dead_count > 4)
                    {
                        ghostIsAlive = false;
                        Logger.Default.Info(ghost + "DEAD");
                    }
                }
                else
                {
                    if (ghost_alive_img_name.Contains("shachong"))
                    {
                        if (moveFlagCount % 4 == 0 && moveFlagCount < 20)
                        {
                            keyPressWithTime(Keys.A, 1200);
                        }
                    }
                    Logger.Default.Info(ghost + "ALIVE");
                    clickCenterMouseRight();
                    clickCenterMouseRight();
                    clickCenterMouseRight();
                    Thread.Sleep(300);
                    keyPressWithTime(Keys.F, 100);
                }

                sleepTagrget(200, 500);
            }
        }

        /// <summary>
        /// 修正X坐标
        /// </summary>
        /// <param name="targetImgName"></param>
        /// <param name="targetName"></param>
        /// <returns></returns>
        public bool modifyUserToTargetPoiX(string targetImgName, Keys direct, int moveMaxCout)
        {
            string targetImgPath = DirTool.Combine(Contact.MolongImgDirPath, targetImgName);
            bool modifySuccessStatus = true;
            bool needModify = true;
            int check_target_img_not_exist_flag = 0;
            int img_not_exist_up_count = 0;
            while (needModify && GlobalStatus.OpenAutoMolong)
            {
                Location loc_target_img = ImgPoiTool.LocateSimple(targetImgPath);
                if (loc_target_img.X == -1)
                {
                    check_target_img_not_exist_flag++;
                    if (check_target_img_not_exist_flag > 3)
                    {
                        if (img_not_exist_up_count < moveMaxCout)
                        {
                            keyPressWithTime(direct, 300);
                            check_target_img_not_exist_flag = 0;
                            img_not_exist_up_count++;
                            Thread.Sleep(300);
                        }
                        //无法修正
                        else
                        {
                            return false;
                        }
                    }
                    Thread.Sleep(300);
                    continue;
                }
                //如果和目标的偏差超过20，则需要移动一下
                int distance = GlobalConfig.CENTER_POI_X - loc_target_img.X;
                Logger.Default.Info(targetImgName + "distance:" + distance);
                if (Math.Abs(distance) > 20)
                {
                    int[] duration = RandomNumTool.GenerateRandomNumbers(100, 400, 1);
                    if (distance > 0)
                    {
                        keyPressWithTime(Keys.A, duration[0]);
                    }
                    else
                    {
                        keyPressWithTime(Keys.D, duration[0]);
                    }
                }
                else
                {
                    needModify = false;
                }
                Thread.Sleep(800);

            }
            return modifySuccessStatus;

        }
        /// <summary>
        /// 修正Y坐标
        /// </summary>
        /// <param name="targetImgName"></param>
        /// <param name="targetName"></param>
        /// <returns></returns>
        public bool modifyUserToTargetPoiY(string targetImgName, Keys direct, int moveMaxCout)
        {
            string targetImgPath = DirTool.Combine(Contact.MolongImgDirPath, targetImgName);
            bool modifySuccessStatus = true;
            bool needModify = true;
            int check_target_img_not_exist_flag = 0;
            int img_not_exist_up_count = 0;
            while (needModify && GlobalStatus.OpenAutoMolong)
            {
                Location loc_target_img = ImgPoiTool.LocateSimple(targetImgPath);
                if (loc_target_img.X == -1)
                {
                    check_target_img_not_exist_flag++;
                    if (check_target_img_not_exist_flag > 3)
                    {
                        if (img_not_exist_up_count < moveMaxCout)
                        {
                            keyPressWithTime(direct, 300);
                            check_target_img_not_exist_flag = 0;
                            img_not_exist_up_count++;
                            Thread.Sleep(500);
                        }
                        //无法修正
                        else
                        {
                            return false;
                        }
                    }
                    continue;
                }
                //如果和目标的偏差超过20，则需要Move一下
                int distance = GlobalConfig.CENTER_POI_Y - loc_target_img.Y;
                Logger.Default.Info(targetImgName + "distance:" + distance);
                if (Math.Abs(distance) > 40)
                {
                    int[] duration = RandomNumTool.GenerateRandomNumbers(100, 400, 1);
                    if (distance > 0)
                    {
                        keyPressWithTime(Keys.W, duration[0]);
                    }
                    else
                    {
                        keyPressWithTime(Keys.S, duration[0]);
                    }
                }
                else
                {
                    needModify = false;
                }
                Thread.Sleep(800);
            }
            return modifySuccessStatus;

        }

        public void keyPressWithTime(Keys key, int time)
        {
            if (GlobalStatus.OpenAutoMolong)
            {
                Contact.MainUI.GetPressKey().KeyDown(key);
                Thread.Sleep(time);
                Contact.MainUI.GetPressKey().KeyUp(key);
                Thread.Sleep(200);
            }
        }

        #endregion


        //OPEN CHECK THREAD
        public void openCheckThread()
        {
            if (!GlobalStatus.OpenCheckThread && GlobalStatus.AppIsRuning)
            {
                Logger.Default.Info("OPEN CHECK ML TASK");
                Thread t = new Thread(checkMlTask);
                t.Start();
            }
        }

        public void checkMlTask()
        {
            // 60s per check
            while (GlobalStatus.AppIsRuning)
            {
                if (GlobalStatus.OpenAutoMolong)
                {
                    checkMlTaskInner();
                }
                Thread.Sleep(60 * 1000);
            }
        }
        public void checkMlTaskInner()
        {
            //MORE THAN 10 MIN DON'T CLEAR FLOOR？
            if (isTimeDifferenceGreaterThanNMinutes(LastClearFloorDateTime, DateTime.Now, 10))
            {
                Logger.Default.Info("MORE THAN 10 MIN ,RUN RESTART");
                //CLOSE BAT
                keyPressWithTime(Keys.F9, 300);
                sleepTagrget(2000, 3000);
                //prevent direct
                prevent_direct();
                //CHECK IS ML MAP?
                if (exitMolong(true))
                {
                    sleepTagrget(6000, 7000);
                    //Open BAT
                    const char F6Key = (char)Keys.F6;
                    keyPressWithTime(Keys.F6, 300);
                }
                else
                {
                    //check ml map?
                    Location loc_molong_flag = getMlMapFlag();
                    if (loc_molong_flag.X == -1)
                    {
                        keyPressWithTime(Keys.F9, 300);
                        sleepTagrget(2000, 3000);
                        //modify poi
                        //bool statusY = modifyUserToTargetPoiY("17_xiaozhen_yzsz.jpg", 'S', 6);
                        //if (statusY)
                        //{
                        //    bool statusX = modifyUserToTargetPoiY("17_xiaozhen_yzsz.jpg", 'A', 6);
                        //    if (statusX)
                        //    {
                        //        //Open BAT
                        //        const char F6Key = (char)Keys.F6;
                        //        keyPressWithTime(F6Key, 300);
                        //    }
                        //}
                    }

                }
            }
        }

        static bool isTimeDifferenceGreaterThanNMinutes(DateTime dateTime1, DateTime dateTime2, int n)
        {
            TimeSpan timeDifference = dateTime2 - dateTime1;
            Logger.Default.Info("LAST SEE DIFFERENCE:" + timeDifference.TotalMinutes + "min");
            return timeDifference.TotalMinutes >= n;
        }

        public void prevent_direct()
        {
            keyPressWithTime(Keys.W, 300);
            keyPressWithTime(Keys.A, 300);
            keyPressWithTime(Keys.S, 300);
            keyPressWithTime(Keys.D, 300);
        }


        #region 模拟鼠标滚动滑轮

        // 定义鼠标事件的API
        [DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

        // 鼠标事件的标志，MOUSEEVENTF_WHEEL 表示鼠标滚轮事件
        private const int MOUSEEVENTF_WHEEL = 0x0800;

        // 模拟鼠标滚轮滚动
        public static void ScrollDown(int amount)
        {
            mouse_event(MOUSEEVENTF_WHEEL, 0, 0, -amount, 0);
        }

        public static void ScrollUp(int amount)
        {
            mouse_event(MOUSEEVENTF_WHEEL, 0, 0, amount, 0);
        }

        #endregion

        #region MergeAndSall
        public void autoMerge()
        {
            //B
            //check wq or zb
            //handle wq

        }

        public void autoSall()
        {
            //space
            //check wq or zb
            //handle wq

            //handle zb
        }
        #endregion

        private void CheckBox_Auto_SC_CheckedChanged(object sender, EventArgs e)
        {
            GlobalStatus.OpenAutoShaChong = CheckBox_Auto_SC.Checked;
        }
    }
}
